package gonz.data.swim;


import gonz.common.Config;
import gonz.common.PriceAndArticleParser;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.util.ArrayList;
import java.util.List;

public class Top {
    public static final Logger log = Logger.getLogger(Top.class);

    //    public static final String[] PRICE_ARTICLE_XPATHS = new String[]{
//            "//div[@id='content']/div/div[2]/div[2]/div[2]/div[2]/div/p[4]",
//            "//div[@id='content']/div/div[2]/div[2]/div[2]/div[2]/div/p[5]",
//            "//div[@id='content']/div/div[2]/div[2]/div/div[2]/div/p[4]",
//            "//div[@id='content']/div/div[2]/div[2]/div[2]/div[2]/div/p[2]",
//            "//div[@id='content']/div/div[2]/div[2]/div[2]/div[2]/div/p[3]",
//            "//div[@id='content']/div/div[2]/div[2]/div/div[2]/div/p[3]",
//            "//div[@id='content']/div/div[2]/div[2]/div/div[2]/div/p[5]",
//            "//div[@id='content']/div/div[2]/div[2]/div/div[2]/div/p[7]",
//            "//div[@id='content']/div/div[2]/div[2]/div/div[2]/div/p[6]"};
    public static final String[] PRICE_XPATHS = new String[]{
            "//div[@id='content']/div/div[2]/form/div/div[2]/div/div/div[3]"};
    public static final String[] ARTICLE_XPATHS = new String[]{
            "//div[@id='content']/div/div[2]/form/div/div[2]/div/div/div[4]",
            "//div[@id='content']/div/div[2]/form/div[2]/div[2]/div/div/div[3]",
            "//div[@id='content']/div/div[2]/form/div/div[2]/div/div/div[3]",
            "//div[@id='content']/div/div[2]/form/div/div[2]/div/div/div[4]"};
    //    public static final String CONTAINER_IMAGES_XPATH = "//div[@id='swatchContainer0']/div";
    public static final String[] CONTAINER_IMAGES_XPATHS = new String[]{
            "/html/body/div[2]/div/div[4]/div/div/div[2]/form/div/div[2]/div/div[2]/div[2]/div/div[3]/div",
            "/html/body/div[2]/div/div[4]/div/div/div[2]/form/div/div[2]/div/div[2]/div[2]/div/div[2]/div",
            "/html/body/div[3]/div/div[4]/div/div/div[2]/form/div[2]/div[2]/div/div[2]/div[2]/div/div[2]/div",
            "/html/body/div[2]/div/div[4]/div/div/div[2]/form/div/div[2]/div/div[2]/div[2]/div/div[4]/div",
            "/html/body/div[2]/div/div[4]/div/div/div[2]/form/div[2]/div[2]/div/div[2]/div[2]/div/div[5]/div",
            "/html/body/div[2]/div/div[4]/div/div/div[2]/form/div/div[2]/div/div[2]/div[2]/div/div[5]/div"
            };
    //    public static final String ALT_IMAGES_XPATH = "//div[@id='altImages']/div/a";
    public static final String ALT_IMAGES_XPATH = "//ul[@id='altImages']/li/a";


    public static final String MAIN_IMAGE_ID = "vsImage";
    public static final String UNKNOWN_PRICES_SYMBOL = "";
    public static final String UNKNOWN_ARTICLE_SYMBOL = "";
    private WebDriver webDriver;

    private List<String> prices;
    private String article;
    private Swim swim;
    private String imgFolder;
    private List<Image> images = new ArrayList<Image>();

    public Top(WebDriver webDriver, Swim swim, String imgFolder) {

        this.webDriver = webDriver;
        this.swim = swim;
        this.imgFolder = imgFolder;
        this.prices = grabPrices();
        this.article = grabArticle();
//        if (!isPriceExists()) {
//            this.price = PriceAndArticleParser.parseAllPrices(pricesAndArticle);
//            if (this.price.equalsIgnoreCase(PriceAndArticleParser.UNKNOWN_SYMBOL))
//                log.error("Price for Top not found. " + webDriver.getCurrentUrl());
//        }
        List<Image> containerImgs = grabContainerImages();

        if (containerImgs.size() == 0) {
            this.images.addAll(grabAlternateImages(false, 1));
        } else {
            this.images.addAll(containerImgs);
//            this.images.addAll(grabAlternateImages("images", true));
        }

        if (!Config.settings.getBoolean(Config.SKIP_ALTERNATE_KEY, true)) {
            this.images.addAll(grabAlternateImages(true, Integer.MAX_VALUE));
        }

        if (this.images.size() == 0) {
            Image mainImage = grabMainImage();
            if (mainImage == null)
                log.error("Image not found. swim link: " + getSwim().getLink());
            else
                this.images.add(mainImage);

        }

    }

    public Swim getSwim() {
        return swim;
    }

    public List<String> getPrices() {
        return prices;
    }

    public String getArticle() {
        return article;
    }

    public List<Image> getImages() {
        return images;
    }

    private List<String> grabPrices() {
        List<String> result = new ArrayList<String>();
        for (int i = 0; i < PRICE_XPATHS.length; i++) {
            try {
                List<WebElement> elements = webDriver.findElements(By.xpath(PRICE_XPATHS[i]));
                if (elements == null || elements.isEmpty()) {
                    log.debug("Can't find top price element: " + PRICE_XPATHS[i]);
                } else {
                    for (WebElement element : elements) {
                        if (element != null && !element.getText().isEmpty()) {
                            result.add(element.getText());
                        }
                    }
                    if (!result.isEmpty()) {
                        log.debug("Top prices has been grabbed: " + PRICE_XPATHS[i] + " Result:" + result);
                        return result;
                    }
                }
            } catch (NoSuchElementException e) {
                log.debug("Can't find top price element: " + PRICE_XPATHS[i]);
            }

        }
        log.error("Can't grab Top prices. " + webDriver.getCurrentUrl());

        result.add(UNKNOWN_PRICES_SYMBOL);
        return result;
    }

    private String grabArticle() {

        for (int i = 0; i < ARTICLE_XPATHS.length; i++) {
            try {
                WebElement element = webDriver.findElement(By.xpath(ARTICLE_XPATHS[i]));
                if (element == null || element.getText().isEmpty())
                    log.debug("Can't find top article element: " + ARTICLE_XPATHS[i]);
                else {
                    if (PriceAndArticleParser.isArticleExist(element.getText())) {
                        log.debug("Top article has been grabbed: " + ARTICLE_XPATHS[i] +
                                " Article:" + element.getText());
                        return element.getText();
                    }
                }
            } catch (NoSuchElementException e) {
                log.debug("Can't find top article element: " + ARTICLE_XPATHS[i]);
            }

        }
        log.error("Can't grab Top article. " + webDriver.getCurrentUrl());
        return UNKNOWN_ARTICLE_SYMBOL;
    }

//    private boolean isPriceExists() {
//        return !(PriceAndArticleParser.UNKNOWN_SYMBOL.equalsIgnoreCase(getPrice()));
//    }

    private List<Image> grabContainerImages() {
        List<Image> images = new ArrayList<Image>();
        List<WebElement> imagesElements = null;

        for (int i = 0; i < CONTAINER_IMAGES_XPATHS.length; i++) {
            try {
                WebElement imagesContainerElement = webDriver.findElement(By.xpath(CONTAINER_IMAGES_XPATHS[i]));
                if (imagesContainerElement == null || imagesContainerElement.getAttribute("data-val") == null ||
                        !imagesContainerElement.getAttribute("data-val").equalsIgnoreCase("color"))
                    log.debug("Can't find top Container Images: " + CONTAINER_IMAGES_XPATHS[i]);
                else {
                    imagesElements = imagesContainerElement.findElements(By.xpath(".//p/a"));
                    //imagesElements = webDriver.findElements(By.xpath(CONTAINER_IMAGES_XPATHS[i]+"/p/a"));
                    break;
                }
            } catch (NoSuchElementException e) {
                log.debug("Can't find top Container Images: " + CONTAINER_IMAGES_XPATHS[i]);
            }

        }

        if (imagesElements == null || imagesElements.size() == 0) {
            log.error("There is no images in container. Skip." + " , swim link: " + getSwim().getLink());
            return images;
        }
        for (int j = 0; j < imagesElements.size(); j++) {
            String imgNameAttr = imagesElements.get(j).getAttribute("data-view");
            if (StringUtils.isBlank(imgNameAttr)) {
                log.warn("Can't find image name in container. Skip. N: " + j + " data-view: " + imgNameAttr + " , swim link: " + getSwim().getLink());
                continue;
            }
//            String imageLink = StringUtils.substringBetween(imgName, "'http://", "'");
//            if (StringUtils.isBlank(imageLink)) {
//                log.error("Can't parse image link in container. Skip. N: " + j + " onclickAttr: " + imgName + " , swim link: " + getSwim().getLink());
//                continue;
//            }
            String imageLink = "http://media.victoriassecret.com/product/428x571/" + imgNameAttr;
            log.debug("N: " + j +" Found image name is:" + imgNameAttr + " link is:" + imageLink + " , swim link: " + getSwim().getLink());
            Image image = new Image(imageLink, this);

            String imgColorAttr = imagesElements.get(j).getAttribute("data-val");
            String color;
            if (StringUtils.isBlank(imgColorAttr)) {
                log.warn("Can't find color in container. Using N. N: " + j + " imgColorAttr: " + imgColorAttr + " , swim link: " + getSwim().getLink());
                color = String.valueOf(j);
            } else {
                color = imgColorAttr;//StringUtils.substringBetween(imgColorAttr, "'");
                log.debug("N: " + j +" Found color is:" + color + " , swim link: " + getSwim().getLink());
            }
            image.setColor(color);
            image.download(imgFolder);
            images.add(image);
        }

        return images;
    }

    private List<Image> grabAlternateImages(boolean skipFirst, int num) {
        List<Image> images = new ArrayList<Image>();
        int startFrom;
        if (skipFirst)
            startFrom = 1;
        else
            startFrom = 0;
        List<WebElement> imageElements = webDriver.findElements(By.xpath(ALT_IMAGES_XPATH));
        if (imageElements == null || imageElements.size() == 0) {
            log.warn("There is no alternate images. Skip. " + " , swim link: " + getSwim().getLink());
            return images;
        }

        if (imageElements.size() < num)
            num = imageElements.size();
        for (int j = startFrom; j < num; j++) {
            String hrefAttr = imageElements.get(j).getAttribute("href");
            if (StringUtils.isBlank(hrefAttr)) {
                log.warn("Can't find alternate image link. Skip. N: " + j + " hrefAttr: " + hrefAttr + " , swim link: " + getSwim().getLink());
                continue;
            }
            String imageLink = hrefAttr;
            if (StringUtils.isBlank(imageLink)) {
                log.error("Can't parse alternate image link. Skip. N: " + j + " hrefAttr: " + hrefAttr + " , swim link: " + getSwim().getLink());
                continue;
            }
            Image image = new Image(imageLink, this);
            image.setColor("alternate " + j);
            image.download(imgFolder);
            images.add(image);
        }
        return images;
    }

    private Image grabMainImage() {
        try {
            WebElement imageElement = webDriver.findElement(By.id(MAIN_IMAGE_ID));
            if (imageElement == null) {
                log.error("Main image not found , swim link: " + getSwim().getLink());
                return null;
            }
            String srcAttr = imageElement.getAttribute("src");
            if (StringUtils.isBlank(srcAttr))
                log.error("Cant find Main image link, srcAttr: " + srcAttr + " , swim link: " + getSwim().getLink());
            Image image = new Image(srcAttr, this);
            image.setColor("main");
            image.download(imgFolder);
            return image;
        } catch (NoSuchElementException e) {
            log.error("Main image not found , swim link: " + getSwim().getLink());
            return null;
        }


    }

}